package com.ak.socketmq.controller;

import com.ak.socketmq.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;


/**
 * 服务端推动的消息
 */
@Controller
@Slf4j
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate template;


    /**
     * 广播推送消息
     */
    @Scheduled(fixedRate = 10000)
    public void sendTopicMessage() {
        log.info("web 后台广播推送！");
        User user = new User();
        user.setName("joker");
        user.setAge(22);
        template.convertAndSend("/topic/getResponse", user);
    }

    /**
     * 一对一推送消息 10秒钟
     */
    @Scheduled(fixedRate = 10000)
    public void sendQueueMessage() {
        // 每次随机向
        int i=new Random().nextInt()%2;
        User user=new User();
        user.setId(String.valueOf(i));
        user.setName("joker");
        user.setAge(10);
        /**
         * 参数一指定客户端接收的用户标识
         * 参数二客户端监听指定通道时，设定的访问服务器的URL
         * 参数三向目标发送消息体（实体、字符串等等）
         */
        log.info("web 一对一推送！"+user.toString());
        template.convertAndSendToUser(user.getId()+"","/queue/getResponse",user);
    }

}